package com.leyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.dto.PageDTO;
import com.leyou.dto.SkuDTO;
import com.leyou.dto.SpuDTO;
import com.leyou.dto.SpuDetailDTO;
import com.leyou.mapper.BrandMapper;
import com.leyou.mapper.SkuMapper;
import com.leyou.mapper.SpuDetailMapper;
import com.leyou.mapper.SpuMapper;
import com.leyou.myException.LyException;
import com.leyou.pojo.*;
import com.leyou.service.*;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.leyou.constants.MQConstants.*;
/**
 * @author jshstart
 * @creat 2020-12-09 17:21
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpuDetailService spuDetailService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    /**
     * 根据条件分页查询
     * @param brandId
     * @param categoryId
     * @param id
     * @param page
     * @param rows
     * @param saleable
     * @return
     */
    @Override
    public PageDTO<SpuDTO> querySpuByPage(Long brandId, Long categoryId, Long id, Integer page, Integer rows, Boolean saleable) {
//        String brandName = null;
//        String cateGoryName=null;
//        if (brandId!=null){
//             brandName = brandService.getById(brandId).getName();
//        }
//        if (categoryId!=null){
//            cateGoryName = categoryService.getById(categoryId).getName();
//        }
        Page<Spu> spuPage = query()
                .eq(!StringUtils.isEmpty(id), "id", id)
                .eq(!StringUtils.isEmpty(brandId), "brand_id", brandId)
                .eq(!StringUtils.isEmpty(categoryId), "cid3", categoryId)
                .eq(saleable != null, "saleable", saleable)
                .page(new Page<>(page,rows));
        List<Spu> spuList = spuPage.getRecords();
        List<SpuDTO> spuDTOList = spuList.stream().map(SpuDTO::new).collect(Collectors.toList());
//        for (SpuDTO spuDTO : spuDTOList) {
//            spuDTO.setBrandName(brandName);
//            spuDTO.setCategoryName(cateGoryName);
//        }
        for (SpuDTO spuDTO : spuDTOList) {
            updateCategoryAndBrandBySpuId(spuDTO);
        }
        PageDTO<SpuDTO> pageDTO = new PageDTO<>();
        pageDTO.setItems(spuDTOList);
        pageDTO.setTotal(spuPage.getTotal());
        pageDTO.setTotalPage(spuPage.getPages());
        return pageDTO;
    }

    /**
     * 用来根据spu获得对应的分类和品牌的名称
     * @param spuDTO
     */
    private void updateCategoryAndBrandBySpuId(SpuDTO spuDTO) {
        String brandName = brandService.getById(spuDTO.getBrandId()).getName();
        spuDTO.setBrandName(brandName);
        List<Long> categoryIds = spuDTO.getCategoryIds();
        List<Category> categoryList = categoryService.listByIds(categoryIds);
        String categoryName = categoryList.stream().map(Category::getName).collect(Collectors.joining("/"));
        spuDTO.setCategoryName(categoryName);
    }


    /**
     * 根据spudto添加商品
     * @param spuDTO
     */
    @Override
    @Transactional
    public void addGood(SpuDTO spuDTO) {
        Spu spu = spuDTO.toEntity(Spu.class);
        spu.setSaleable(false);
        this.save(spu);
        Long spuId = spu.getId();
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
       // List<Sku> skuList = skuDTOList.stream().map(skuDTO -> new Sku()).collect(Collectors.toList());
        for (SkuDTO  skuDTO  : skuDTOList) {
            System.out.println("skuDTO = " + skuDTO);
            Sku sku = skuDTO.toEntity(Sku.class);
            sku.setSpuId(spuId);
            sku.setSold(0L);
            sku.setSaleable(false);
            skuService.save(sku);
        }
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = spuDetailDTO.toEntity(SpuDetail.class);
        spuDetail.setSpuId(spuId);
        spuDetailService.save(spuDetail);
    }

    /**
     * 修改商品
     * @param spuDTO
     */
    @Override
    @Transactional
    public void updateGood(SpuDTO spuDTO) {
        Spu spu = spuDTO.toEntity(Spu.class);
        Boolean isSuccesful = null;
        //修改spu
        if (spu.getId()!=null) {
            this.updateById(spu);
        }
        //修改spudetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        if (spuDetailDTO!=null&&spuDetailDTO.getSpuId()!=null) {
            SpuDetail spuDetail = spuDetailDTO.toEntity(SpuDetail.class);
            spuDetailService.updateById(spuDetail);
        }
        //修改sku，如果里面包含saleable，就需要把sku删除，不包含就执行修改或添加
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        Map<Boolean, List<Sku>> skuMap = skuDTOList.stream().map(skuDTO -> skuDTO.toEntity(Sku.class))
                .collect(Collectors.groupingBy(sku -> sku.getSaleable() != null));
        List<Sku> deleteSpu = skuMap.get(true);
        if (!CollectionUtils.isEmpty(deleteSpu)){
            List<Long> deleteSkuIds = deleteSpu.stream().map(sku -> sku.getId()).collect(Collectors.toList());
           isSuccesful= skuService.removeByIds(deleteSkuIds);
        }
        List<Sku> updateSku = skuMap.get(false);
        if (!CollectionUtils.isEmpty(updateSku)){
            // List<Long> deleteSkuIds = updateSku.stream().map(sku -> sku.getId()).collect(Collectors.toList());
            isSuccesful= skuService.saveOrUpdateBatch(updateSku);
            System.out.println(isSuccesful);
        }
//        if (skuDTOList!=null) {
//            for (SkuDTO skuDTO : skuDTOList) {
//                if (skuDTO.getSpuId()!=null) {
//                    System.out.println("skuDTO = " + skuDTO);
//                    Sku sku = skuDTO.toEntity(Sku.class);
//                    skuService.updateById(sku);
//                }else {
//                    throw new LyException(500,"spuId不能为null");
//                }
//            }
//        }
    }


    /**
     * 修改商品上架或者下架
     * @param id
     * @param saleable
     */
    @Override
    public void updateSaleableBySpuId(Long id, Boolean saleable) {
        Boolean successful;
        this.baseMapper.updateSaleableBySpuId(id,saleable);
        successful=  skuService.update().set("saleable",saleable).eq("spu_id",id).update();
        if (!successful){
            throw new LyException(500,"sku表修改上下架失败");
        }
//        String routingKey=saleable?RoutingKeyConstants.ITEM_UP_KEY:RoutingKeyConstants.ITEM_DOWN_KEY;
//        amqpTemplate.convertAndSend(ExchangeConstants.ITEM_EXCHANGE_NAME,routingKey,id);
        // 3.发送MQ消息
        String routingKey = saleable ? RoutingKeyConstants.ITEM_UP_KEY : RoutingKeyConstants.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ExchangeConstants.ITEM_EXCHANGE_NAME, routingKey, id);
    }

    /**
     * 根据商品id查询spu，sku，spudetail
     * @param id
     * @return
     */
    @Override
    public SpuDTO queryAllBySpuId(Long id) {
        Spu spu = getById(id);
        List<Sku> skuList = skuService.query().eq("spu_id", id).list();
        SpuDetail spuDetail = spuDetailService.query().eq("spu_id", id).one();
        SpuDTO spuDTO = new SpuDTO(spu);
//        spuDTO.setCategoryName(categoryService.getById(spu.getCid3()).getName());
//        spuDTO.setBrandName(brandService.getById(spu.getBrandId()).getName());
        updateCategoryAndBrandBySpuId(spuDTO);
        spuDTO.setSpuDetail(new SpuDetailDTO(spuDetail));
        spuDTO.setSkus(skuList.stream().map(SkuDTO::new).collect(Collectors.toList()));
        return spuDTO;
    }


}

